<template>
  <div>
    <el-dialog title="分配权限" :model-value="authorityToAssignDialogVisible" @open="handleOpen" :before-close="handleCancel"
      width="30%">
      <el-form :model="formData" :rules="rules" label-width="80px" ref="authorityToAssignForm">
        <el-form-item label="权限:" prop="checkedAuthorityIds">
          <el-tree-select v-model="formData.checkedAuthorityIds"
          :data="formCfg.authorityTree" :render-after-expand="false"
            :default-expand-all="true"
          :multiple="true"
          show-checkbox
          style="width: 240px;"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel()">取消</el-button>
        <el-button type="primary" @click="confirmCheck()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script setup name='AuthorityToAssign' lang='ts'>
import { ref,reactive } from 'vue'
import { queryTreeApi } from '@/api/authorityApi';
import { queryByIdApi } from '@/api/roleApi';
import type { AnyObjsDefine } from '@/types/common';
import { ElMessage } from 'element-plus';

let formData = reactive({
  checkedAuthorityIds: [] as string[]
})

let rules = reactive({
  checkedAuthorityIds: [
    { required: false,  trigger: 'blur' }
  ]
})
let formCfg = reactive({
  authorityTree:[] as AnyObjsDefine,
})
let authorityToAssignForm = ref()
const props = defineProps<{ authorityToAssignDialogVisible: boolean, idToAssign: string }>()
let emitter = defineEmits(["closeDialog", "confirmCheck"])
   // 打开对话框
const handleOpen = () => {
  queryTreeApi().then(result => {
    formCfg.authorityTree = result.data
  })
  // 查询角色明细回显已有权限
  queryByIdApi(props.idToAssign).then(result => {
    formData.checkedAuthorityIds = result.data.authorityIds
  })
}
// 取消
function handleCancel() {
  authorityToAssignForm.value.resetFields()
  emitter("closeDialog")
}
// 确认选择
function confirmCheck(){
  if (formData.checkedAuthorityIds && formData.checkedAuthorityIds.length > 0) {
    emitter("confirmCheck", formData.checkedAuthorityIds)
  } else {
    ElMessage({ message: "请先选择权限", type: "warning" })
  }
}
</script>
<style scoped>
   
</style>